package com.etc


import org.apache.spark.ml.classification.LogisticRegressionModel
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.mllib.classification.{LogisticRegressionWithLBFGS, LogisticRegressionWithSGD}
import org.apache.spark.mllib.evaluation.MulticlassMetrics
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.sql.SparkSession


/**
  * 随机梯度下降的线性回归模型
  *
  *
  * 胃癌转移
  *
  *
  * 数据特征
  * y:肾细胞癌转移情况（有转移y=1；无转移y=0）
  * x1:确诊时患者的年龄（岁）
  * x2:肾细胞癌血管内皮生长因子（VEGF）其阳性表述由低到高共三个等级
  * x3:肾细胞癌组织内微血管数(MVC）
  * x4:肾癌细胞核组织学分级，由低到高共4级
  * x5:肾癌细胞分期，由低到高共4期。
  * y x1 x2 x3 x4 x5
  * 0 1:59 2:2 3:43.4 4:2 5:1

  *
  *
  */
object LogisticRegressionTest2 {


  def main(args: Array[String]): Unit = {


    val conf = new SparkConf().setAppName("logisticRegression").setMaster("local")
    val sc  = new SparkContext(conf)
    val data  = MLUtils.loadLibSVMFile(sc , "wa.txt")

    val Array(traning,test) = data.randomSplit(Array(0.8,0.2),seed = 1L)

    println(traning.count ,test.count)
    traning.foreach(println)

    val model = new LogisticRegressionWithLBFGS()
      .setNumClasses(2)
      .run(traning)

    val labelAndPreds = test.map{ point =>
      val prediction = model.predict(point.features)
      (point.label, prediction)
    }

    println("推荐"+model.weights)


    labelAndPreds.foreach(println)
    val trainErr = labelAndPreds.filter( r => r._1 != r._2).count.toDouble / test.count
    println("容错率为trainErr： " +trainErr)


    val predictionAndLabels = test.map{                           //计算测试值
      case LabeledPoint(label,features) =>
        val prediction = model.predict(features)
        (prediction,label)                                              //存储测试值和预测值
    }
    val metrics = new MulticlassMetrics(predictionAndLabels)           //创建验证类
    val precision = metrics.precision                                   //计算验证值
    println("Precision= "+precision)

    val patient = Vectors.dense(Array(20,1,0.0,1,1))

    val d = model.predict(patient)

    print("预测的结果为:" + d)

    //计算患者可能性
    if(d == 1){
      println("患者的胃癌有几率转移。 ")
    } else {
      println("患者的胃癌没有几率转移 。")
    }


  }
}
